import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart' as http;
import 'package:me_code_flutter/components/user/drawer_user.dart';
import 'dart:async';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:simple_search_bar/simple_search_bar.dart';
import './model.dart';
import './code_detail.dart';
import 'add_code.dart';

class CodeBook extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: CodeBookHome(),
        floatingActionButton: FloatingActionButton(
          child: Icon(Icons.add),
          onPressed: () {
            Navigator.of(context).push(MaterialPageRoute(
                builder: (context) => AddCode(
                    item: Post('', '', '', '', '', '', '', '', '', ''))));
          },
        ));
  }
}

class CodeBookHome extends StatefulWidget {
  @override
  _CodeBookHomeState createState() => _CodeBookHomeState();
}

class _CodeBookHomeState extends State<CodeBookHome> {
  final AppBarController appBarController = AppBarController();
  String _searchTex;
  String _url = 'https://me.yuanqiao.pw/api/me/getList.php?limit=20';
  Timer _timer;
  // 当前页数
  int _page = 1;
  // 页面数据
  List _list = [];
  // 是否还有
  bool _hasMore = true;
  // 滚动控制器
  ScrollController _scrollController = new ScrollController();
  @override
  void initState() {
    super.initState();
    this._getData();
    // 监听滚动事件
    _scrollController.addListener(() {
      // 获取滚动条下拉的距离
      // print(_scrollController.position.pixels);
      // 获取整个页面的高度
      // print(_scrollController.position.maxScrollExtent);
      if (_scrollController.position.pixels >
          _scrollController.position.maxScrollExtent - 40) {
        this._getData();
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    if (_timer != null) {
      _timer.cancel();
    }
  }

  Future _getData() async {
    if (this._hasMore) {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      String requestUrl = _url + '&offset=' + ((_page - 1) * 20).toString();
      if (_searchTex != null) {
        requestUrl = requestUrl + '&website=' + _searchTex;
      }
      // 获取数据
      final codeResponse = await http.get(
        requestUrl,
        headers: {HttpHeaders.authorizationHeader: prefs.get('user_token')},
      );
      if (this.mounted) {
        if (codeResponse.statusCode == 200) {
          final codeResponseBody = json.decode(codeResponse.body);
          if (codeResponseBody['state'] != '1') {
            Navigator.of(context).pushNamedAndRemoveUntil(
              '/login',
              (route) => route == null,
            );
          } else {
            List<Post> posts = codeResponseBody['data']
                .map<Post>((item) => Post.fromJson(item))
                .toList();
            if (this.mounted) {
              setState(() {
                // 拼接数据
                this._list.addAll(posts);
                // 页数累加
                this._page++;
              });
            }
            if (posts.length < 20) {
              if (this.mounted) {
                setState(() {
                  // 关闭加载
                  this._hasMore = false;
                });
              }
            }
            return posts;
          }
        } else {
          Fluttertoast.showToast(
              msg: '网络或服务器错误',
              toastLength: Toast.LENGTH_SHORT,
              gravity: ToastGravity.CENTER,
              timeInSecForIosWeb: 1,
              backgroundColor: Colors.white,
              textColor: Colors.black87,
              fontSize: 16.0);
        }
      }
    }
  }

  // 下拉刷新
  Future<void> _onRefresh() async {
    this._hasMore = true;
    this._page = 1;
    this._list = [];
    // 持续两秒
    await Future.delayed(Duration(milliseconds: 2000), () {
      this._getData();
    });
  }

  // 加载动画
  Widget _getMoreWidget() {
    // 如果还有数据
    if (this._hasMore) {
      return Center(
        child: Padding(
          padding: EdgeInsets.all(10.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Text(
                '加载中',
                style: TextStyle(fontSize: 16.0),
              ),
              // 加载图标
              SizedBox(
                child: CircularProgressIndicator(strokeWidth: 1.0),
                height: 20.0,
                width: 20.0,
              )
            ],
          ),
        ),
      );
    } else {
      String txt = "...到底了...";
      if (this._list.length == 0) {
        txt = this._searchTex != '' ? '...未找到匹配项...' : "...还没有添加数据...";
      } else if (this._list.length < 20) {
        txt = "...暂无更多数据...";
      }
      return Center(
          child: Container(
        padding: EdgeInsets.only(bottom: 35),
        child: Text(txt, style: TextStyle(color: Colors.black38)),
      ));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        child: Scaffold(
            resizeToAvoidBottomInset: false,
            drawer: DrawerUser(),
            appBar: PreferredSize(
              preferredSize: Size.fromHeight(55.6),
              child: SearchAppBar(
                primary: Theme.of(context).primaryColor,
                appBarController: appBarController,
                // You could load the bar with search already active
                autoSelected: false,
                searchHint: "搜索网站名...",
                // initialQuery: _searchTex,
                mainTextColor: Colors.white,
                onChange: (String value) {
                  if (_timer != null) {
                    _timer.cancel();
                  }
                  if (_searchTex != value) {
                    _timer = new Timer(const Duration(milliseconds: 1200), () {
                      this._hasMore = true;
                      this._page = 1;
                      this._list = [];
                      this._searchTex = value;
                      this._getData();
                    });
                  }
                  //Your function to filter list. It should interact with
                  //the Stream that generate the final list
                },
                //Will show when SEARCH MODE wasn't active
                mainAppBar: AppBar(
                  toolbarHeight: 80,
                  centerTitle: true,
                  automaticallyImplyLeading: false, // 去除返回按钮
                  title: Text("密码本"),
                  leading: Builder(builder: (BuildContext context) {
                    return IconButton(
                      icon: Icon(Icons.menu, color: Colors.white, size: 22.0),
                      onPressed: () {
                        Scaffold.of(context).openDrawer();
                      },
                      tooltip: MaterialLocalizations.of(context)
                          .openAppDrawerTooltip, //打开抽屉drawer
                    );
                  }),
                  actions: <Widget>[
                    Container(
                      padding: EdgeInsets.only(top: 5.0, right: 10.0),
                      child: InkWell(
                        child: Icon(
                          Icons.search,
                        ),
                        onTap: () {
                          // This is where You change to SEARCH MODE. To hide, just
                          // add FALSE as value on the stream
                          appBarController.stream.add(true);
                        },
                      ),
                    )
                  ],
                ),
              ),
            ),
            body: this._list.length == 0
                ? this._getMoreWidget()
                : RefreshIndicator(
                    // 下拉刷新事件
                    onRefresh: this._onRefresh,
                    child: ListView.builder(
                        // 上拉加载控制器
                        controller: _scrollController,
                        itemCount: this._list.length,
                        itemBuilder: (context, index) {
                          Widget tip = Text("");
                          // 当渲染到最后一条数据时，加载动画提示
                          if (index == this._list.length - 1) {
                            tip = _getMoreWidget();
                          }
                          return Column(children: <Widget>[
                            ListTile(
                              title: Text(this._list[index].website),
                              subtitle: Text(this._list[index].username),
                              onTap: () {
                                Navigator.push(context, MaterialPageRoute(
                                    //注意传递的参数。goods_list[index]，是吧索引下的item 数据传递了
                                    builder: (context) {
                                  return MeCodeDetail(item: this._list[index]);
                                }));
                              },
                            ),
                            Divider(),
                            // 加载提示
                            tip
                          ]);
                        }))));
  }
}
